package com.project8.main;

import java.lang.reflect.Method;

import android.graphics.Color;
import android.graphics.PorterDuff;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

public class Search {
	
	ImageButton searchButton;
	Button closeButton;
	EditText searchbar;
	TextView pageNum;
	TextView chapterInfo;
	boolean searchBegun = false;
	
	public Search (ImageButton searchBut, Button closeBut, EditText search, TextView page, TextView chapter) 
    {
		searchButton = searchBut;
		closeButton = closeBut;
		searchbar = search;
		pageNum = page;
		chapterInfo = chapter;
		
        searchbar.setVisibility(View.INVISIBLE);
        closeButton.setVisibility(View.INVISIBLE);
    }
	
	public void showSearchBar()
	{
		closeButton.setVisibility(View.VISIBLE);
		searchbar.setVisibility(View.VISIBLE);
		closeButton.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
		pageNum.setVisibility(View.GONE);
		chapterInfo.setVisibility(View.GONE);
		
		searchbar.setText("");
		searchbar.setHint("Search");
	}
	
	public void hideSearchBar(WebView bookContent)
	{
		pageNum.setVisibility(View.VISIBLE);
		chapterInfo.setVisibility(View.VISIBLE);
		closeButton.setVisibility(View.INVISIBLE);
		searchbar.setVisibility(View.INVISIBLE);
				
		searchBegun = false;
		
		try
		{
			bookContent.findAll("");
		    Method m = WebView.class.getMethod("setFindIsUp", Boolean.TYPE);
		    m.invoke(bookContent, false);
		}
		catch (Throwable ignored){}
	}
	
	
	public void doSearch(WebView bookContent, View button)
	{     
    	if(button.equals(searchButton))
    	{
    		if(!searchbar.getText().toString().equals(""))
    		{
    			System.out.println("Searching for string: " + searchbar.getText().toString());
    			System.out.println("Search Begun: " + searchBegun);
    			
    			if(searchBegun)
    			{
    				//bookContent.findAll(searchbar.getText().toString());
    				bookContent.findNext(true);
    			}
    			else
    			{
    				int numEntries = bookContent.findAll(searchbar.getText().toString());
    				bookContent.findAll(searchbar.getText().toString());
    				System.out.println("Number of Occurrences = " + numEntries);
    			}
    			searchBegun = true;
						
    			try
    			{
    				Method m = WebView.class.getMethod("setFindIsUp", Boolean.TYPE);
    				m.invoke(bookContent, true);
    			}
    			catch (Throwable ignored){}
    		}
    	}
	}
	
	public void doSearch2(WebView bookContent, String string)
    {     
    	if(!string.equals(""))
    	{   			
    		bookContent.findAll(string);
						
    		try
    		{
    			Method m = WebView.class.getMethod("setFindIsUp", Boolean.TYPE);
    			m.invoke(bookContent, true);
    		}
       		catch (Throwable ignored){}
    	}
    }

	public void resetSearchProgress()
	{
		searchBegun = false;
	}
}
